package com.way.fileexplorer.activities;

import java.io.File;
import java.util.ArrayList;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.way.fileexplorer.R;
import com.way.fileexplorer.adapters.MultiSelectFileAdapter;
import com.way.fileexplorer.adapters.QuickScanCursorAdapter;
import com.way.fileexplorer.util.ActivityUtils;
import com.way.fileexplorer.util.ActivityUtils.CopyFileListener;
import com.way.fileexplorer.util.FileDeleteTask;
import com.way.fileexplorer.util.FileType;
import com.way.fileexplorer.util.FileUtilTask.OnFinishCallBack;
import com.way.fileexplorer.util.IStorageUtil.StorageChangedListener;
import com.way.fileexplorer.util.IntentUtil;
import com.way.fileexplorer.util.StorageUtil;

public class MultiSelectActivity extends Activity implements OnClickListener,
		OnItemClickListener {
    
    private static final String TAG = "MultiSelectActivity";
    
    public static final int MULTI_DELETE = 20;
    private static final int FILE_LIMIT = 10;
    
	private ListView mListView;
	private MultiSelectFileAdapter mAdapter;
	private QuickScanCursorAdapter mAdapterForOverView;
	private CheckBox mSelectAllFileCb;
	private ArrayList<File> mSelectedFiles = new ArrayList<File>();
	private TextView selectAllFileTx;
	
	private CopyFileListener mCopyFileListener;
    
    StorageChangedListener mStorageChangedListener = new StorageChangedListener() {

        @Override
        public void onStorageChanged(String path, boolean available) {
            Log.d(TAG, "StorageChanged: path = " + path + " available = " + available);
            if(available) {
                return;
            }
            new Handler(getMainLooper()).postDelayed(new Runnable() {

                @Override
                public void run() {
                    finish();
                }
            }, 1000);
        }
    };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.multi_select_activity);
		StorageUtil.addStorageChangeListener(mStorageChangedListener);
		mListView = (ListView) findViewById(R.id.list);
		mSelectAllFileCb = (CheckBox) findViewById(R.id.select_all_cb);
		selectAllFileTx = (TextView) findViewById(R.id.selece_all_file);
		mSelectAllFileCb.setOnClickListener(this);
		ActionBar actionbar = getActionBar();
		actionbar.setDisplayOptions(ActionBar.DISPLAY_HOME_AS_UP | ActionBar.DISPLAY_SHOW_TITLE);
		if (getIntent().getStringExtra("path") != null) {
			String path = getIntent().getStringExtra("path");
			int top = getIntent().getIntExtra("position", 0);
			if (path != null) {
				File file = new File(path);
				mAdapter = new MultiSelectFileAdapter(this,mListView);
				mAdapter.init(file);
				mListView.setAdapter(mAdapter);
				mListView.setSelection(top);
				mListView.setOnItemClickListener(this);
			}
		} else if (getIntent().hasExtra("fileType")) {
			int fileType = getIntent().getIntExtra("fileType", -1);
			int top = getIntent().getIntExtra("position", 0);
			switch (fileType) {
			case FileType.FILE_TYPE_IMAGE:
				mAdapterForOverView = new QuickScanCursorAdapter(this,
						QuickScanCursorAdapter.RESOURCE_IMAGE, top,
						mListView, true);
				break;
			case FileType.FILE_TYPE_AUDIO:
				mAdapterForOverView = new QuickScanCursorAdapter(this,
						QuickScanCursorAdapter.RESOURCE_AUDIO, top,
						mListView, true);
				break;
			case FileType.FILE_TYPE_VIDEO:
				mAdapterForOverView = new QuickScanCursorAdapter(this,
						QuickScanCursorAdapter.RESOURCE_VIDEO, top,
						mListView, true);
				break;
			case FileType.FILE_TYPE_DOC:
                mAdapterForOverView = new QuickScanCursorAdapter(this,
                        QuickScanCursorAdapter.RESOURCE_DOC, top,
                        mListView, true);
				break;
			case FileType.FILE_TYPE_PACKAGE:
                mAdapterForOverView = new QuickScanCursorAdapter(this,
                        QuickScanCursorAdapter.RESOURCE_APK, top,
                        mListView, true);
			}
			mListView.setAdapter(mAdapterForOverView);
			mListView.setOnItemClickListener(this);
			this.invalidateOptionsMenu();
		}
		mCopyFileListener = new CopyFileListener(this);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (mAdapter != null) {
			if (mAdapter.isChecked(position)) {
				if (mAdapter.isAllChecked()) {
					mSelectAllFileCb.setChecked(false);
					selectAllFileTx.setText(R.string.select_all);
				}
				mAdapter.setChecked(position, false);
				mSelectedFiles.remove(mAdapter.getItem(position));
			} else {
				mSelectedFiles.add((File) mAdapter.getItem(position));
				mAdapter.setChecked(position, true);
				if (mSelectedFiles.size() == mAdapter.getCount()) {
					mSelectAllFileCb.setChecked(true);
					selectAllFileTx.setText(R.string.unselect_all);
				}
			}
			this.invalidateOptionsMenu();
			mAdapter.notifyDataSetChanged();
		} else if (mAdapterForOverView != null) {
			if (mAdapterForOverView instanceof QuickScanCursorAdapter) {
				if (mAdapterForOverView.isChecked(position)) {
					if (mAdapterForOverView.isAllChecked()) {
						mSelectAllFileCb.setChecked(false);
						selectAllFileTx.setText(R.string.select_all);
					}
					mAdapterForOverView.setChecked(position, false);
					mSelectedFiles.remove(mAdapterForOverView.getFile(position));
				} else {
					mSelectedFiles.add(mAdapterForOverView.getFile(position));
					mAdapterForOverView.setChecked(position, true);
					if (mSelectedFiles.size() == mAdapterForOverView.getCount()) {
						mSelectAllFileCb.setChecked(true);
						selectAllFileTx.setText(R.string.unselect_all);
					}
				}
				mAdapterForOverView.notifyDataSetChanged();
			}
			this.invalidateOptionsMenu();
		}

	}

    @Override
    protected void onResume() {
        super.onResume();
        if (mSelectAllFileCb != null) {
            if (mAdapter != null) {
                mSelectAllFileCb.setChecked(mAdapter.isAllChecked());
            } else if (mAdapterForOverView != null) {
                mSelectAllFileCb.setChecked(mAdapterForOverView.isAllChecked());
            }
        }
    }

	@Override
	protected void onDestroy() {
        if (mAdapter != null) {
            mAdapter.destroyThread();
            mAdapter = null;
        }
        if (mAdapterForOverView != null) {
            mAdapterForOverView.destroyThread();
            mAdapterForOverView = null;
        }
        StorageUtil.removeStorageChangeListener(mStorageChangedListener);
	    super.onDestroy();
	}
	
	@Override
	public void onClick(View v) {
		if (v != mSelectAllFileCb) {
		    return;
		}
        if (mAdapter != null) {
            if (mAdapter.isAllChecked() == true) {
                selectAllFileTx.setText(R.string.select_all);
                mSelectedFiles.clear();
                mAdapter.checkAll(false);
            } else {
                selectAllFileTx.setText(R.string.unselect_all);
                mSelectedFiles.clear();
                for (int i = 0; i < mAdapter.getCount(); i++) {
                    mSelectedFiles.add((File) mAdapter.getItem(i));
                }
                mAdapter.checkAll(true);
            }
            mAdapter.notifyDataSetChanged();
        } else if (mAdapterForOverView != null) {
            if (mAdapterForOverView instanceof QuickScanCursorAdapter) {
                if (mSelectAllFileCb.isChecked()) {
                    mSelectAllFileCb.setChecked(true);
                    selectAllFileTx.setText(R.string.unselect_all);
                    mSelectedFiles.clear();
                    for (int i = 0; i < mAdapterForOverView.getCount(); i++) {
                        mSelectedFiles.add((File) mAdapterForOverView.getFile(i));
                    }
                    mAdapterForOverView.checkAll(true);
                }else {
                    mSelectAllFileCb.setChecked(false);
                    selectAllFileTx.setText(R.string.select_all);
                    mSelectedFiles.clear();
                    mAdapterForOverView.checkAll(false);
                }
                mAdapterForOverView.notifyDataSetChanged();
            } 
        }
        invalidateOptionsMenu();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.multi_select_menu, menu);
		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		if (menu != null) {
			MenuItem multiSelectItem = menu.findItem(R.id.menu_delete);
			MenuItem copySelectItem = menu.findItem(R.id.menu_copy);
			MenuItem cutSelectItem = menu.findItem(R.id.menu_cut);
			MenuItem installSelectItem = menu.findItem(R.id.menu_install);
			MenuItem shareSelectItem = menu.findItem(R.id.menu_share);
			if(getIntent().getIntExtra("fileType", -1) != FileType.FILE_TYPE_PACKAGE){
			    if(installSelectItem != null){
			        installSelectItem.setVisible(false);
			    }
			}
			if(mAdapterForOverView == null){
			    if(shareSelectItem != null){
				shareSelectItem.setVisible(false);
			    }
			}
			if (mSelectedFiles != null && !mSelectedFiles.isEmpty()) {
				if (multiSelectItem != null) {
					multiSelectItem.setEnabled(true);
				}
				if (copySelectItem != null) {
					copySelectItem.setEnabled(true);
				}
				if (cutSelectItem != null) {
					cutSelectItem.setEnabled(true);
				}
				if(shareSelectItem != null && shareSelectItem.isVisible()){
				    shareSelectItem.setEnabled(true);
				}
				if(installSelectItem != null && installSelectItem.isVisible()){
					installSelectItem.setEnabled(true);
				}
			} else {
				if (multiSelectItem != null) {
					multiSelectItem.setEnabled(false);
				}
				if (copySelectItem != null) {
					copySelectItem.setEnabled(false);
				}
				if (cutSelectItem != null) {
					cutSelectItem.setEnabled(false);
				}
				if(installSelectItem != null){
					if(installSelectItem.isVisible()){
	                    			installSelectItem.setEnabled(false);
	                		}
				}
				if(shareSelectItem != null){
					if(shareSelectItem.isVisible()){
	                    			shareSelectItem.setEnabled(false);
	                		}
				}
			}
		}
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    int itemId = item.getItemId();
		switch (itemId) {
		case R.id.menu_delete: {
		    new AlertDialog.Builder(this)
            .setTitle(R.string.operate_delete)
            .setMessage(R.string.confirm_delete)
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener(){
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    new FileDeleteTask.Build(MultiSelectActivity.this, false)
                    .addOperateFiles(mSelectedFiles)
                    .setOnFinishCallBack(new OnFinishCallBack() {

                        @Override
                        public void onFinish(boolean cancelTask) {
                            if(!cancelTask) {
                                finish();
                            }
                        }
                        
                    }).creatTask().start();
                }
                
            })
            .setNegativeButton(android.R.string.cancel, null)
            .show();
			return true;
		}
		case R.id.menu_copy: 
		case R.id.menu_cut: {
		    mCopyFileListener.setCut(itemId == R.id.menu_cut);
		    mCopyFileListener.addOpFiles(mSelectedFiles);
            if(StorageUtil.getExternalStorageState()){
                ActivityUtils.showDestSelectDialog(this, mCopyFileListener);
            }else{
                mCopyFileListener.onClick(null, 0);
            }
            return true;
		}
		
		case R.id.menu_install:{
			if(mAdapterForOverView != null && mSelectedFiles != null && !mSelectedFiles.isEmpty()){
			    if(mSelectedFiles.size() > FILE_LIMIT){
	                Toast.makeText(this, getString(R.string.install_apk_limited, FILE_LIMIT), Toast.LENGTH_SHORT).show();
	                return true;
	            }
                for(File file: mSelectedFiles){
                    Intent intent = IntentUtil.getIntentByFileType(MultiSelectActivity.this, FileType.FILE_TYPE_PACKAGE, file);
                    if(intent != null) {
                        startActivity(intent);
                    } else {
                        Toast.makeText(MultiSelectActivity.this, R.string.msg_invalid_intent, Toast.LENGTH_SHORT).show();
                    }
                }
                finish();
            }
			
			return true;
		}
		case R.id.menu_share:{
		    if(mSelectedFiles.size() > FILE_LIMIT){
		        Toast.makeText(this, getString(R.string.share_file_limited, FILE_LIMIT), Toast.LENGTH_SHORT).show();
		        return true;
		    }
            Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
            String type = FileType.getFileType(this).getTypeByFile(mSelectedFiles.get(0));
            ArrayList<Uri> sharedUris = new ArrayList<Uri>();
            for(File file : mSelectedFiles){
                sharedUris.add(Uri.fromFile(file));
            }
            intent.setType(type);
            intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, sharedUris);
            startActivity(Intent.createChooser(intent, this.getResources().getString(R.string.operate_share)));
            finish();
            return true;
		}
		case android.R.id.home:{
			onBackPressed();
			return true;
		}
		default:
		    return false;
		}
		//return super.onOptionsItemSelected(item);
	}
}
